﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Xml;
using Enring;
using Enring.Controls;
using System.Data;

namespace System.Web.Mvc.Html
{
    public static class DataListExtensions
    {
        /// <summary>
        /// Create a datalist object in the page
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="configFilename"></param>
        /// <returns></returns>
        public static MvcHtmlString WisGridView(this HtmlHelper helper)
        {
            XmlDocument config = XmlHelper.GetConfigration(helper.ViewContext.HttpContext.Request[Const.DefaultConfigKey]);
            //Find the view node
            string guid = helper.ViewContext.HttpContext.Request["viewid"];
            string xpath = Enring.UI.IsGuid(guid) ? "//View[@guid='{0}']" : "//View[@id='{0}']";
            DataListControl dl = new DataListControl(config.SelectSingleNode(string.Format(xpath,guid)),helper.ViewContext,helper.ViewData);            
            return new MvcHtmlString(dl.GetHtml());
        }

        public static MvcHtmlString WisForm(this HtmlHelper helper)
        {
            XmlDocument config = XmlHelper.GetConfigration(helper.ViewContext.HttpContext.Request[Const.DefaultConfigKey]);
            //Find the view node
            string guid = helper.ViewContext.HttpContext.Request["formid"];
            DataFormControl form = new DataFormControl(config.SelectSingleNode(string.Format("//Form[@guid='{0}']", guid)), helper.ViewContext,helper.ViewData);
            return new MvcHtmlString(form.GetHtml());
        }

        public static MvcHtmlString RowData(this HtmlHelper helper, string key)
        {
            if (helper.ViewData["data"] != null)
            {
                DataSet ds = helper.ViewData["data"] as DataSet;
                if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                    return new MvcHtmlString(ds.Tables[0].Rows[0][key].ToString());
                else
                    return new MvcHtmlString("NONE");
            }
            else
                return new MvcHtmlString("NONE");
        }
    }
}